package cn.com.generaldata.os.util;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import cn.com.generaldata.os.constant.FilterConstant;
import cn.com.generaldata.os.paging.Filter;
import cn.com.generaldata.os.paging.FilterRule;

public class FilterUtils {

	public static DetachedCriteria parseFilter(Filter rules, DetachedCriteria criteria) {

		for (FilterRule rule : rules.getRules()) {
			switch (rule.getSearchType()) {
			case FilterConstant.EQUAL:
				criteria.add(Restrictions.eq(rule.getFieldName(), rule.getValue()));
				break;
			case FilterConstant.LIKE:
				criteria.add(Restrictions.like(rule.getFieldName(), rule.getValue()));
				break;
			case FilterConstant.LT:
				criteria.add(Restrictions.lt(rule.getFieldName(), rule.getValue()));
				break;
			case FilterConstant.GT:
				criteria.add(Restrictions.gt(rule.getFieldName(), rule.getValue()));
				break;
			case FilterConstant.COLLECTION:
				criteria.add(Restrictions.in(rule.getFieldName(), (Object[]) rule.getValue()));
				break;
			case FilterConstant.NOT_EQUAL:
				criteria.add(Restrictions.or(Restrictions.ne(rule.getFieldName(), rule.getValue()),
						Restrictions.isNull(rule.getFieldName())));
				break;
			case FilterConstant.LE:
				criteria.add(Restrictions.le(rule.getFieldName(), rule.getValue()));
				break;
			case FilterConstant.GE:
				criteria.add(Restrictions.ge(rule.getFieldName(), rule.getValue()));
				break;
			case FilterConstant.GET_NULL:
				criteria.add(Restrictions.isNull(rule.getFieldName()));
				break;
			case FilterConstant.NOT_NULL:
				criteria.add(Restrictions.isNotNull(rule.getFieldName()));
				break;
			case FilterConstant.UNCOLLECTION:
				criteria.add(Restrictions.not(Restrictions.in(rule.getFieldName(), (Object[]) rule.getValue())));
				break;
			case FilterConstant.OR:
				criteria.add(Restrictions.or(Restrictions.isNull(rule.getFieldName()),
						Restrictions.eq(rule.getFieldName(), rule.getValue())));
				break;
			case FilterConstant.ORVALUE:
				criteria.add(Restrictions.or(Restrictions.eq(rule.getFieldName(), rule.getValue2()),
						Restrictions.eq(rule.getFieldName(), rule.getValue())));
				break;
			}
		}

		if (StringUtils.isNotBlank(rules.getSortBy())) {
			switch (rules.getOrder()) {
			case FilterConstant.ASC:
				criteria.addOrder(Order.asc(rules.getSortBy()));
				break;
			case FilterConstant.DESC:
				criteria.addOrder(Order.desc(rules.getSortBy()));
				break;
			}
		}

		return criteria;
	}

}
